import { useMemo } from 'react'
import { HTML5Backend } from 'react-dnd-html5-backend'
import { DndProvider } from 'react-dnd'
import { defaultQuery } from '@/store/modules/core'
import useWidget from '@/hooks/useWidget'
import useQuery from '@/pages/bi-core/hooks/useQuery'
import DataField from './DataField'
import DataQuery from './DataQuery'
import styles from '../index.module.less'

const Dataset = () => {
  const { widgets, selectedWidgetIds, selectedWidget } = useWidget()
  const { setWidgets, chartQuery } = useQuery(widgets)

  const query = useMemo(() => selectedWidget.query || defaultQuery, [selectedWidget])

  const onDatasetIdChange = (id) => {
    onQueryChange({
      ...query,
      datasetId: id
    })
  }

  const onValueChange = (value) => {
    onQueryChange(value)
  }

  const onQueryChange = (value) => {
    console.log(selectedWidget)
    setWidgets(widgets, selectedWidgetIds[0], value)
  }

  const onQuery = async () => {
    chartQuery(widgets, selectedWidgetIds[0], query)
  }

  return (
    <div className={styles.dataset}>
      <DndProvider backend={HTML5Backend}>
        <DataField value={query.datasetId} onChange={onDatasetIdChange} />
        <DataQuery
          selectedWidget={selectedWidget}
          value={query}
          onChange={onValueChange}
          onUpdate={onQuery}
        />
      </DndProvider>
    </div>
  )
}

export default Dataset
